#!/usr/bin/perl -w
use strict;
use XML::LibXML;
use File::Basename;

# This script is called thus :
#
#   make_opengl [opengl_version]
#
#     - It needs files from the OpenGL extension registry:
#
#       https://raw.github.com/KhronosGroup/OpenGL-Registry/master/xml/gl.xml
#       https://raw.github.com/KhronosGroup/OpenGL-Registry/master/xml/wgl.xml
#       https://raw.github.com/KhronosGroup/EGL-Registry/refs/heads/main/api/egl.xml
#
#       If they are not found in the current directory the script will
#       attempt to download them from there.
#
#     - opengl_version is the OpenGL version emulated by the library
#       (can be 1.0 to 1.5). The default is 1.1.
#
# This script generates the following files :
#
#     - opengl32.spec : the spec file giving all the exported functions
#       of the OpenGL32.DLL library. These functions are the one an
#       application can directly link to (and are all the functions
#       defined in the OpenGL core for the version defined by
#       'opengl_version').
#
#     - include/wine/wgl_driver.h: definitions for the tables of OpenGL functions.
#
#
# Copyright 2000 Lionel Ulmer
# Copyright 2012 Alexandre Julliard
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#

#
# Files to generate
#
my $spec_file = "opengl32.spec";
my $wgl_file = "../../include/wine/wgl.h";

# If set to 1, generate TRACEs for each OpenGL function
my $gen_traces = 1;

#
# List of norm categories
#
my %cat_1_0 = ( "GL_VERSION_1_0" => 1 );
my %cat_1_1 = ( %cat_1_0, "GL_VERSION_1_1" => 1 );
my %cat_1_2 = ( %cat_1_1, "GL_VERSION_1_2" => 1 );
my %cat_1_3 = ( %cat_1_2, "GL_VERSION_1_3" => 1 );
my %cat_1_4 = ( %cat_1_3, "GL_VERSION_1_4" => 1 );
my %cat_1_5 = ( %cat_1_4, "GL_VERSION_1_5" => 1 );

my %norm_categories = ();

#
# This hash table gives the conversion between OpenGL types and
# the .spec type and debug format
#
my %arg_types =
    (
     "GLbitfield" =>           [ "long",   "%d" ],
     "GLboolean" =>            [ "long",   "%d" ],
     "GLbyte" =>               [ "long",   "%d" ],
     "GLchar" =>               [ "long",   "%c" ],
     "GLcharARB" =>            [ "long",   "%c" ],
     "GLclampd" =>             [ "double", "%f" ],
     "GLclampf" =>             [ "float",  "%f" ],
     "GLclampx" =>             [ "long",   "%d" ],
     "GLdouble" =>             [ "double", "%f" ],
     "GLeglClientBufferEXT" => [ "ptr",    "%p" ],
     "GLeglImageOES" =>        [ "ptr",    "%p" ],
     "GLenum" =>               [ "long",   "%d" ],
     "GLfixed" =>              [ "long",   "%d" ],
     "GLfloat" =>              [ "float",  "%f" ],
     "GLhalfNV" =>             [ "long",   "%d" ],
     "GLhandleARB" =>          [ "long",   "%d" ],
     "int" =>                  [ "long",   "%d" ],
     "GLint" =>                [ "long",   "%d" ],
     "GLint64" =>              [ "int64",  "wine_dbgstr_longlong(%s)" ],
     "GLint64EXT" =>           [ "int64",  "wine_dbgstr_longlong(%s)" ],
     "GLintptr" =>             [ "long",   "%Id" ],
     "GLintptrARB" =>          [ "long",   "%Id" ],
     "GLshort" =>              [ "long",   "%d" ],
     "GLsizei" =>              [ "long",   "%d" ],
     "GLsizeiptr" =>           [ "long",   "%Id" ],
     "GLsizeiptrARB" =>        [ "long",   "%Id" ],
     "GLstring" =>             [ "str",    "wine_dbgstr_a(%s)" ],
     "GLsync" =>               [ "ptr",    "%p" ],
     "GLubyte" =>              [ "long",   "%d" ],
     "GLuint" =>               [ "long",   "%d" ],
     "GLuint64" =>             [ "int64",  "wine_dbgstr_longlong(%s)" ],
     "GLuint64EXT" =>          [ "int64",  "wine_dbgstr_longlong(%s)" ],
     "GLushort" =>             [ "long",   "%d" ],
     "GLvdpauSurfaceNV" =>     [ "long",   "%Id" ],
     "GLDEBUGPROC" =>          [ "ptr",    "%p" ],
     "GLDEBUGPROCARB" =>       [ "ptr",    "%p" ],
     "GLDEBUGPROCAMD" =>       [ "ptr",    "%p" ],
     "GLDEBUGPROCKHR" =>       [ "ptr",    "%p" ],
     "GLVULKANPROCNV" =>       [ "ptr",    "%p" ],
     "HDC" =>                  [ "long",   "%p" ],
     "HGLRC" =>                [ "long",   "%p" ],
     "HPBUFFERARB" =>          [ "long",   "%p" ],
     "HENHMETAFILE" =>         [ "long",   "%p" ],
     "LPGLYPHMETRICSFLOAT" =>  [ "ptr",    "%p" ],
     "LPCSTR" =>               [ "str",    "wine_dbgstr_a(%s)" ],
     "UINT" =>                 [ "long",   "%u" ],
     "DWORD" =>                [ "long",   "%lu" ],
     "BOOL" =>                 [ "long",   "%u" ],
     "FLOAT" =>                [ "float",  "%f" ],
    );

my %remap_types =
    (
     "HGLRC" => "struct wgl_context *",
     "HPBUFFERARB" => "struct wgl_pbuffer *",
    );

my %khronos_types =
    (
     "double" => "double DECLSPEC_ALIGN(8)",
     "khronos_int8_t" => "signed char",
     "khronos_uint8_t" => "unsigned char",
     "khronos_int16_t" => "short",
     "khronos_uint16_t" => "unsigned short",
     "khronos_int32_t" => "int",
     "khronos_uint32_t" => "unsigned int",
     "khronos_int64_t" => "__int64",
     "khronos_uint64_t" => "unsigned __int64",
     "khronos_ssize_t" => "ssize_t",
     "khronos_float_t" => "float",
     "khronos_utime_nanoseconds_t" => "unsigned __int64",
     "khronos_stime_nanoseconds_t" => "__int64",
    );

my %manual_win_functions =
    (
     "glDebugEntry" => 1,
     "wglChoosePixelFormat" => 1,
     "wglCreateLayerContext" => 1,
     "wglDescribeLayerPlane" => 1,
     "wglDescribePixelFormat" => 1,
     "wglGetCurrentContext" => 1,
     "wglGetCurrentDC" => 1,
     "wglGetCurrentReadDCARB" => 1,
     "wglGetDefaultProcAddress" => 1,
     "wglGetLayerPaletteEntries" => 1,
     "wglRealizeLayerPalette" => 1,
     "wglSetLayerPaletteEntries" => 1,
     "wglSwapLayerBuffers" => 1,
     "wglUseFontBitmapsA" => 1,
     "wglUseFontBitmapsW" => 1,
     "wglUseFontOutlinesA" => 1,
     "wglUseFontOutlinesW" => 1,
    );
my %manual_win_thunks =
    (
     "glGetString" => 1,
     "glGetStringi" => 1,
     "glMapBuffer" => 1,
     "glMapBufferARB" => 1,
     "glMapBufferRange" => 1,
     "glMapNamedBuffer" => 1,
     "glMapNamedBufferEXT" => 1,
     "glMapNamedBufferRange" => 1,
     "glMapNamedBufferRangeEXT" => 1,
     "glUnmapBuffer" => 1,
     "glUnmapBufferARB" => 1,
     "glUnmapNamedBuffer" => 1,
     "glUnmapNamedBufferEXT" => 1,
     "wglChoosePixelFormatARB" => 1,
     "wglGetExtensionsStringARB" => 1,
     "wglGetExtensionsStringEXT" => 1,
     "wglGetPixelFormat" => 1,
     "wglGetPixelFormatAttribfvARB" => 1,
     "wglGetPixelFormatAttribivARB" => 1,
     "wglGetProcAddress" => 1,
     "wglQueryCurrentRendererStringWINE" => 1,
     "wglQueryRendererStringWINE" => 1,
     "wglSwapBuffers" => 1,
    );
my %manual_unix_thunks =
    (
     "glClear" => 1,
     "glDebugMessageCallback" => 1,
     "glDebugMessageCallbackAMD" => 1,
     "glDebugMessageCallbackARB" => 1,
     "glDrawBuffer" => 1,
     "glDrawBuffers" => 1,
     "glDrawPixels" => 1,
     "glFinish" => 1,
     "glFlush" => 1,
     "glFramebufferDrawBufferEXT" => 1,
     "glFramebufferDrawBuffersEXT" => 1,
     "glFramebufferReadBufferEXT" => 1,
     "glGetBooleanv" => 1,
     "glGetDoublev" => 1,
     "glGetFloatv" => 1,
     "glGetFramebufferParameterivEXT" => 1,
     "glGetInteger64v" => 1,
     "glGetIntegerv" => 1,
     "glGetString" => 1,
     "glGetStringi" => 1,
     "glNamedFramebufferDrawBuffer" => 1,
     "glNamedFramebufferDrawBuffers" => 1,
     "glNamedFramebufferReadBuffer" => 1,
     "glReadBuffer" => 1,
     "glReadPixels" => 1,
     "glViewport" => 1,
     "wglGetProcAddress" => 1,
     "wglSwapBuffers" => 1,
    );
my %hide_default_fbo_thunks =
    (
     "glFramebufferRenderbuffer" => 1,
     "glFramebufferRenderbufferEXT" => 1,
     "glFramebufferTexture" => 1,
     "glFramebufferTexture1D" => 1,
     "glFramebufferTexture1DEXT" => 1,
     "glFramebufferTexture2D" => 1,
     "glFramebufferTexture2DEXT" => 1,
     "glFramebufferTexture3D" => 1,
     "glFramebufferTexture3DEXT" => 1,
     "glFramebufferTextureARB" => 1,
     "glFramebufferTextureEXT" => 1,
     "glFramebufferTextureFaceARB" => 1,
     "glFramebufferTextureFaceEXT" => 1,
     "glFramebufferTextureLayer" => 1,
     "glFramebufferTextureLayerARB" => 1,
     "glFramebufferTextureLayerEXT" => 1,
     "glFramebufferTextureMultiviewOVR" => 1,
     "glGetFramebufferAttachmentParameteriv" => 1,
     "glGetFramebufferAttachmentParameterivEXT" => 1,
    );
my %resolve_default_fbo_thunks =
    (
     "glCopyColorTable" => 1,
     "glCopyPixels" => 1,
     "glCopyTexImage1D" => 1,
     "glCopyTexImage2D" => 1,
     "glCopyTexSubImage1D" => 1,
     "glCopyTexSubImage2D" => 1,
     "glCopyTexSubImage3D" => 1,
     "glCopyTextureSubImage1D" => 1,
     "glCopyTextureSubImage2D" => 1,
     "glCopyTextureSubImage3D" => 1,
     "glReadPixels" => 1,
    );
my %map_default_fbo_thunks =
    (
     "glBindFramebuffer" => [ "framebuffer" ],
     "glBindFramebufferEXT" => [ "framebuffer" ],
     "glBlitNamedFramebuffer" => [ "readFramebuffer", "drawFramebuffer" ],
     "glCheckNamedFramebufferStatus" => [ "framebuffer" ],
     "glCheckNamedFramebufferStatusEXT" => [ "framebuffer" ],
     "glClearNamedFramebufferfi" => [ "framebuffer" ],
     "glClearNamedFramebufferfv" => [ "framebuffer" ],
     "glClearNamedFramebufferiv" => [ "framebuffer" ],
     "glClearNamedFramebufferuiv" => [ "framebuffer" ],
     "glGetNamedFramebufferAttachmentParameteriv" => [ "framebuffer" ],
     "glGetNamedFramebufferAttachmentParameterivEXT" => [ "framebuffer" ],
     "glGetNamedFramebufferParameterfvAMD" => [ "framebuffer" ],
     "glGetNamedFramebufferParameteriv" => [ "framebuffer" ],
     "glGetNamedFramebufferParameterivEXT" => [ "framebuffer" ],
     "glInvalidateNamedFramebufferData" => [ "framebuffer" ],
     "glInvalidateNamedFramebufferSubData" => [ "framebuffer" ],
     "glNamedFramebufferParameteri" => [ "framebuffer" ],
     "glNamedFramebufferParameteriEXT" => [ "framebuffer" ],
     "glNamedFramebufferSampleLocationsfvARB" => [ "framebuffer" ],
     "glNamedFramebufferSampleLocationsfvNV" => [ "framebuffer" ],
     "glNamedFramebufferSamplePositionsfvAMD" => [ "framebuffer" ],
    );
my %manual_wow64_wrappers =
    (
     "glClientWaitSync" => 0,
     "glDeleteSync" => 0,
     "glFenceSync" => 0,
     "glGetBufferPointerv" => 0,
     "glGetBufferPointervARB" => 0,
     "glGetNamedBufferPointerv" => 0,
     "glGetNamedBufferPointervEXT" => 0,
     "glGetSynciv" => 0,
     "glIsSync" => 0,
     "glMapBuffer" => 1,
     "glMapBufferARB" => 1,
     "glMapBufferRange" => 1,
     "glMapNamedBuffer" => 1,
     "glMapNamedBufferEXT" => 1,
     "glMapNamedBufferRange" => 1,
     "glMapNamedBufferRangeEXT" => 1,
     "glUnmapBuffer" => 1,
     "glUnmapBufferARB" => 1,
     "glUnmapNamedBuffer" => 1,
     "glUnmapNamedBufferEXT" => 1,
     "glWaitSync" => 0,
    );
my %pointer_array_count =
    (
     "glCompileShaderIncludeARB" => "count",
     "glCreateShaderProgramv" => "count",
     "glGetUniformIndices" => "uniformCount",
     "glMultiDrawElements" => "drawcount",
     "glMultiDrawElementsBaseVertex" => "drawcount",
     "glMultiDrawElementsEXT" => "primcount",
     "glMultiModeDrawElementsIBM" => "primcount",
     "glTransformFeedbackVaryings" => "count",
     "glTransformFeedbackVaryingsEXT" => "count",
     "glShaderSource" => "count",
     "glShaderSourceARB" => "count",
     "glBindBuffersRange" => "count",
     "glBindVertexBuffers" => "count",
     "glDrawCommandsNV" => "count",
     "glVertexArrayVertexBuffers" => "count",
     "glDrawCommandsStatesNV" => "count",
     "glListDrawCommandsStatesClientNV" => "count",
    );
my %pointer_is_offset =
    (
     "glGetPointerv" => "params",
     "glGetPointervEXT" => "params",
     "glGetVertexAttribPointerv" => "pointer",
     "glGetVertexAttribPointervARB" => "pointer",
    );
my %state_attrib_funcs =
    (
     "glViewport" => "GL_VIEWPORT, &params->x, 2 * sizeof(GLint) + 2 * sizeof(GLsizei)",
     "glEnable" => "params->cap, &const_true, sizeof(const_true)",
     "glDisable" => "params->cap, &const_false, sizeof(const_false)",
     "glHint" => "params->target, &params->mode, sizeof(params->mode)",
     "glDepthFunc" => "GL_DEPTH_FUNC, &params->func, sizeof(params->func)",
     "glShadeModel" => "GL_SHADE_MODEL, &params->mode, sizeof(params->mode)",
     "glClearColor" => "GL_COLOR_CLEAR_VALUE, &params->red, 4 * sizeof(GLfloat)",
     "glLightModelfv" => "params->pname, PARAMSPTR(params->params), 0 /* variable size */",
     "glLightModeli" => "params->pname, &params->param, sizeof(params->param)",
    );

#
# Used to convert some types
#
sub ConvertType($)
{
    my $arg = shift;
    my $ret = $arg->textContent();
    my @type = $arg->findnodes("./ptype");

    if (@type)
    {
        my $type = $type[0]->textContent();
        $ret =~ s/$type/$remap_types{$type}/ if defined $remap_types{$type};
    }
    return $ret;
}

sub get_func_trace($$$)
{
    my ($name, $func, $param_names) = @_;
    my $trace_fmt = "";
    my $trace_arg = "";
    foreach my $arg (@{$func->[1]})
    {
        my $ptype = get_arg_type( $arg );
        my $pname = get_arg_name( $arg );
        my $param = $arg->textContent();
        if ($param =~ /\*/ || $param =~ /\[/)
        {
            $trace_fmt .= ", ";
            $trace_fmt .= "$pname " if $param_names;
            $trace_fmt .= "%p";
            $trace_arg .= ", $pname";
        }
        elsif (defined $arg_types{$ptype})
        {
            my $format = ${$arg_types{$ptype}}[1];
            $trace_fmt .= ", ";
            $trace_fmt .= "$pname " if $param_names;
            $trace_fmt .= ($format =~ /^%/ ? $format : "%s");
            $trace_arg .= ", " . (sprintf $format =~ /^%/ ? "%s" : $format, $pname);
        }
        else { printf "Unknown type %s in %s\n", $param, $name; }
    }
    $trace_fmt =~ s/^, //;
    $trace_fmt = "($trace_fmt)" unless $param_names;
    return "TRACE( \"$trace_fmt\\n\"$trace_arg );\n";
}

sub get_func_args($$)
{
    my ($func, $convert_args) = @_;
    my $ret = "";
    foreach my $arg (@{$func->[1]})
    {
        my $ptype = get_arg_type( $arg );
        my $pname = get_arg_name( $arg );
        $ret .= " " . ($convert_args ? ConvertType( $arg ) : $arg->textContent()) . ",";
    }
    $ret =~ s/,$/ /;
    $ret ||= "void";
    return $ret;
}

sub get_func_ret($$)
{
    my ($func, $convert_args) = @_;
    my $ret = $convert_args ? ConvertType( $func->[0] ) : $func->[0]->textContent();
    $ret =~ s/ $//;
    return $ret;
}

sub generate_unix_thunk($$$$)
{
    my ($name, $func, $is_wow64, $prefix) = @_;
    my $func_ret = get_func_ret( $func, 0 );
    my $manual_wow64_wrapper = $is_wow64 && defined $manual_wow64_wrappers{$name};
    my $need_wrap = $manual_wow64_wrapper || needs_wrapper( $name, $func );
    my $need_lock = $func_ret =~ /HGLRC|HPBUFFERARB/;
    my $teb = $is_wow64 ? "teb" : "params->teb";
    my $ret_stat = "return STATUS_SUCCESS;";
    my $input_conv = "";
    my $output_conv = "";
    my $call_args = "";
    my $ret_expr = "";
    my $use_dc = 0;
    my $ret = "";

    foreach my $arg (@{$func->[1]})
    {
        $need_lock = 1 if $arg->textContent() =~ /HGLRC|HPBUFFERARB/;
    }

    $ret .= "static NTSTATUS ";
    $ret .= "wow64_" if $is_wow64;
    $ret .= "$prefix\_$name( void *args )\n";
    $ret .= "{\n";

    # special case for functions that take an HDC as first parameter
    $use_dc = @{$func->[1]} && get_arg_type( ${$func->[1]}[0] ) eq "HDC" && $name !~ /wglMake(Context)?Current/;

    $ret_expr = "params->ret = " if !is_void_func( $func );
    $call_args .= " $teb," if $need_wrap;
    if ($is_wow64)
    {
        my $need_manual_thunk = 0;
        $ret .= "    struct\n    {\n";
        $ret .= "        PTR32 teb;\n";
        foreach my $arg (@{$func->[1]})
        {
            my $arg_type = get_arg_type( $arg );
            my $ptype = get_wow64_arg_type( $arg_type );
            my $pname = get_arg_name( $arg );
            $ret .= "        $ptype $pname;\n";

            if ($ptype ne "PTR32")
            {
                $call_args .= " params->$pname,";
            }
            elsif (defined $pointer_array_count{$_} && ($arg_type =~ /\*.*\*/ || $arg_type =~ /(sizei|int)ptr.*\*/))
            {
                if ($arg_type =~ /\*const\*$/)
                {
                    $arg_type =~ s/\*const\*$/**/;
                }
                elsif (!(($arg_type =~ /\*\*$/)))
                {
                    $arg_type =~ s/^const //;
                }
                $input_conv .= "    $arg_type$pname = copy_wow64_ptr32s( params->$pname, params->$pointer_array_count{$_} );\n";
                $output_conv .= "    free( $pname );\n";
                $call_args .= " $pname,";
            }
            elsif (defined $pointer_is_offset{$_} && $pname =~ $pointer_is_offset{$_})
            {
                $arg_type =~ s/\*$//;
                $input_conv .= "    $arg_type$pname\_arg;\n";
                $output_conv .= "    *(PTR32 *)UlongToPtr(params->$pname) = PtrToUlong( $pname\_arg );\n";
                $call_args .= " &$pname\_arg,";
            }
            elsif ($arg_type =~ /(sizei|int)ptr/)
            {
                $call_args .= " (" . $arg_type . ")ULongToPtr(params->$pname),";
            }
            else
            {
                $call_args .= " ULongToPtr(params->$pname),";
                $need_manual_thunk = 1 if $arg_type =~ /(\*.*\*|(sizei|int)ptr.*\*)/;
                $need_lock = 1 if $arg_type =~ /GLsync/;
            }
        }
        if (!is_void_func($func))
        {
            my $ret_type = get_arg_type( $func->[0] );
            my $ptype = get_wow64_arg_type( $ret_type );
            $ret .= "        $ptype ret;\n";
            if ($ret_type eq "const GLubyte *" || $ret_type eq "const char *" || $ret_type eq "const GLchar *")
            {
                $input_conv .= "    " . $ret_type . "ret;\n";
                $ret_expr = "ret = ";
                $ret_stat = "return return_wow64_string( ret, &params->ret );";
            }
            elsif ($ptype eq "PTR32")
            {
                $ret_expr .= "(UINT_PTR)" unless $ret_type =~ /\*/;
                $need_manual_thunk = 1 if $ret_type =~ /(GLsync|PROC|GLintptr|\*)/;
            }
        }
        if ($manual_wow64_wrappers{$name})
        {
            $ret .= "        PTR32 client_ptr;\n";
            $call_args .= " &params->client_ptr,";
        }
        $ret .= "    } *params = args;\n";
        if (!$need_wrap && $need_manual_thunk)
        {
            $ret .= "    FIXME( \"params %p stub!\\n\", params );\n";
            $ret .= "    return STATUS_NOT_IMPLEMENTED;\n";
            $ret .= "}\n\n";
            return $ret;
        }
        $ret .= "    TEB *teb = get_teb64( params->teb );\n" if $need_wrap || !$use_dc;
    }
    else
    {
        foreach my $arg (@{$func->[1]})
        {
            my $ptype = get_arg_type( $arg );
            my $pname = get_arg_name( $arg );
            if (!$need_wrap && defined $remap_types{$ptype})
            {
                $call_args .= " ($remap_types{$ptype})params->$pname,";
            }
            else
            {
                $call_args .= " params->$pname,";
            }
        }
        $ret .= "    struct $name\_params *params = args;\n";
    }
    $ret .= $input_conv;
    if ($use_dc)
    {
        my $param = "params->" . get_arg_name( ${$func->[1]}[0] );
        $param = "ULongToPtr($param)" if $is_wow64;
        $ret .= "    const struct opengl_funcs *funcs = get_dc_funcs( $param );\n";
        $ret .= "    if (!funcs || !funcs->p_$name) return STATUS_NOT_IMPLEMENTED;\n";
    }
    elsif (!$need_wrap)
    {
        $ret .= "    const struct opengl_funcs *funcs = $teb->glTable;\n";
    }
    foreach my $arg (@{$map_default_fbo_thunks{$name}})
    {
        my $target = "GL_DRAW_FRAMEBUFFER";
        $target = "GL_READ_FRAMEBUFFER" if $arg =~ "readFramebuffer";
        $target = "params->target" if $call_args =~ "params->target";
        $ret .= "    if (!params->$arg) params->$arg = get_default_fbo( $teb, $target );\n";
    }
    $ret .= "    resolve_default_fbo( $teb, TRUE );\n" if defined $resolve_default_fbo_thunks{$name};
    $ret .= "    push_default_fbo( $teb );\n" if defined $hide_default_fbo_thunks{$name};
    $ret .= "    pthread_mutex_lock( &wgl_lock );\n" if $need_lock;
    $ret .= "    $ret_expr";
    $call_args =~ s/,$/ /;
    if ($manual_wow64_wrapper)
    {
        $ret .= "wow64_$name($call_args);\n";
    }
    elsif ($need_wrap)
    {
        $ret .= "wrap_$name($call_args);\n";
    }
    else
    {
        $ret .= "($func_ret)" if defined $remap_types{$func_ret};
        $ret .= "funcs->p_$name($call_args);\n";
    }
    $ret .= "    pthread_mutex_unlock( &wgl_lock );\n" if $need_lock;
    $ret .= "    set_current_fbo( $teb, params->target, params->framebuffer );\n" if $name =~ /glBindFramebuffer/;
    $ret .= "    pop_default_fbo( $teb );\n" if defined $hide_default_fbo_thunks{$name};
    if (defined $state_attrib_funcs{$name})
    {
        my $state_args = $state_attrib_funcs{$name};
        if ($is_wow64)
        {
            $state_args =~ s/PARAMSPTR/UlongToPtr/g;
        }
        else
        {
            $state_args =~ s/PARAMSPTR//g;
        }
        $ret .= "    set_context_attribute( $teb, $state_args );\n";
    }
    elsif ($name !~ /^wgl|^glGet|^glIs[A-Z]|^glAre[A-Z]/)
    {
        $ret .= "    set_context_attribute( $teb, -1 /* unsupported */, NULL, 0 );\n";
    }
    $ret .= $output_conv;
    $ret .= "    $ret_stat\n";
    $ret .= "}\n\n";

    return $ret;
}

sub generate_wrapper_declaration($$$)
{
    my ($name, $func, $is_wow64) = @_;
    my $decl_args = get_func_args( $func, 0 );
    my $ret_type = get_func_ret( $func, 0 );
    my $ret = "extern ";
    $ret_type = "PTR32" if $is_wow64 && $ret_type =~ /\*/;
    $ret .= $ret_type;
    $ret .= $is_wow64 ? " wow64_" : " wrap_";
    $ret .= "$name( TEB *teb,";
    foreach my $arg (@{$func->[1]})
    {
        my $ptype = get_arg_type( $arg );
        my $pname = get_arg_name( $arg );
        if ($is_wow64 && ($ptype =~ /\*.*\*/ || $ptype =~ /(sizei|int)ptr.*\*/))
        {
            $ret .= " PTR32 *$pname,";
            next;
        }
        $ret .= " " . $arg->textContent() . ",";
    }
    $ret .= " PTR32 *client_ptr," if $manual_wow64_wrappers{$name};
    $ret =~ s/,$/ /;
    $ret .= ");\n";
    return $ret;
}

sub generate_win_thunk($$)
{
    my ($name, $func) = @_;
    my $decl_args = get_func_args( $func, 0 );
    my $func_ret = get_func_ret( $func, 0 );
    my $params = "";
    my $ret = "";

    $ret .= "$func_ret WINAPI $name($decl_args)\n";
    $ret .= "{\n";
    $ret .= "    struct $name\_params args";
    $params .= " .teb = NtCurrentTeb()";
    foreach my $arg (@{$func->[1]})
    {
        my $pname = get_arg_name( $arg );
        $params .= ", .$pname = $pname";
    }
    $ret .= " = {$params }";
    $ret .= ";\n";
    $ret .= "    NTSTATUS status;\n";
    $ret .= "    " . get_func_trace( $name, $func, 1 ) if $gen_traces;
    $ret .= "    if ((status = UNIX_CALL( $name, &args ))) WARN( \"$name returned %#lx\\n\", status );\n";
    $ret .= "    return args.ret;\n" unless is_void_func($func);
    $ret .= "}\n";

    return $ret;
}

sub get_wow64_arg_type($)
{
    my $ptype = shift;
    return "void" if $ptype =~ /^void$/;
    return "PTR32" if $ptype =~ /(PROC|sizeiptr|intptr|\*|\[)/;
    return $ptype unless defined $arg_types{$ptype};
    return "PTR32" if ${$arg_types{$ptype}}[0] =~ /(ptr|str)/;
    return "PTR32" if ${$arg_types{$ptype}}[1] =~ /%p/;
    return $ptype;
}

sub generate_null_func($$)
{
    my ($name, $func) = @_;
    my $decl_args = get_func_args( $func, 1 );
    my $func_ret = get_func_ret( $func, 1 );
    my $ret = "";

    $ret .= "static $func_ret null_$name($decl_args)\n";
    $ret .= "{\n";
    $ret .= "    ERR( \"unsupported\\n\" );\n";
    if ($name eq "glGetError")
    {
        $ret .= "    return GL_INVALID_OPERATION;\n";
    }
    elsif (!is_void_func( $func ))
    {
        $ret .= "    return 0;\n";
    }
    $ret .= "}\n";
    return $ret;
}

sub generate_spec_entry($$)
{
    my ($name, $func) = @_;
    my $args=" ";
    foreach my $arg (@{$func->[1]})
    {
        my $ptype = get_arg_type( $arg );
        my $param = $arg->textContent();
        if ($param =~ /[[*]/) {
            $args .= "ptr ";
        } elsif (defined($arg_types{$ptype})) {
            $args .= "$@$arg_types{$ptype}[0] ";
        } else {
            die "No conversion for func $name type $param\n";
        }
    }
    $args = substr($args,1,-1);
    return "@ stdcall $_($args)";
}

sub generate_func_params($$)
{
    my ($name, $func) = @_;
    my $ret = "";
    $ret .= sprintf "struct %s_params\n{\n", $name;
    $ret .= "    TEB *teb;\n";
    foreach my $arg (@{$func->[1]})
    {
        my $ptype = get_arg_type( $arg );
        if ($ptype =~ /\]$/)
        {
            $ptype =~ s/\[.*//;
            $ret .= "    $ptype*" . get_arg_name( $arg ) . ";\n";
            next;
        }
        $ret .= sprintf "    %s;\n", $arg->textContent();
    }
    $ret .= sprintf "    %sret;\n", $func->[0]->textContent() unless is_void_func($func);
    $ret .= "#ifndef _WIN64\n    void *client_ptr;\n#endif\n" if $manual_wow64_wrappers{$name};
    $ret .= "};\n\n";
    return $ret;
}

sub is_void_func($)
{
    my $func = shift;
    return 0 if @{$func->[0]->findnodes("./ptype")};
    return $func->[0]->textContent() eq "void ";
}

sub get_arg_type($)
{
    my $p = (shift)->cloneNode(1);
    my @name = $p->findnodes("./name");
    $p->removeChild(@name) if @name;
    my $ret = $p->textContent();
    $ret =~ s/^ +//;
    $ret =~ s/ +$//;
    return $ret;
}

sub get_arg_name($)
{
    my $p = shift;
    my @name = $p->findnodes("./name");
    return $name[0]->textContent();
}

#
# Extract and checks the number of arguments
#
if (@ARGV > 1) {
    my $name0=$0;
    $name0=~s%^.*/%%;
    die "Usage: $name0 [version]\n";
}
my $version = $ARGV[0] || "1.1";
if ($version eq "1.0") {
    %norm_categories = %cat_1_0;
} elsif ($version eq "1.1") {
    %norm_categories = %cat_1_1;
} elsif ($version eq "1.2") {
    %norm_categories = %cat_1_2;
} elsif ($version eq "1.3") {
    %norm_categories = %cat_1_3;
} elsif ($version eq "1.4") {
    %norm_categories = %cat_1_4;
} elsif ($version eq "1.5") {
    %norm_categories = %cat_1_5;
} else {
    die "Incorrect OpenGL version.\n";
}

#
# Fetch the registry files
#
my $ogl_url="https://raw.githubusercontent.com/KhronosGroup/OpenGL-Registry";
my $ogl_commit="03e1bfb87c4664d34dc7822fb591841eec747094";
my $egl_url="https://raw.githubusercontent.com/KhronosGroup/EGL-Registry";
my $egl_commit="bd4838f57cd7e0cb6e4a4154919af426b038695d";
my $cache = ($ENV{XDG_CACHE_HOME} || "$ENV{HOME}/.cache") . "/wine";

system "mkdir", "-p", $cache;
-f "$cache/gl-$ogl_commit.xml" || system "wget", "-q", "-O", "$cache/gl-$ogl_commit.xml", "$ogl_url/$ogl_commit/xml/gl.xml" || die "cannot download gl.xml";
-f "$cache/wgl-$ogl_commit.xml" || system "wget", "-q", "-O", "$cache/wgl-$ogl_commit.xml", "$ogl_url/$ogl_commit/xml/wgl.xml" || die "cannot download wgl.xml";
-f "$cache/egl-$egl_commit.xml" || system "wget", "-q", "-O", "$cache/egl-$egl_commit.xml", "$egl_url/$egl_commit/api/egl.xml" || die "cannot download egl.xml";
chdir(dirname($0));

#
# Then, create the list of all OpenGL functions using the registry
# files. This will create two hash-tables, one with all the function
# whose category matches the one listed in '@norm_categories', the other
# with all other functions.
#
# An element of the hash table is a reference to an array with these
# elements :
#
#  - XML node of the function prototype
#
#  - reference to an array of XML nodes giving the list of arguments (an empty array
#    for a 'void' function).
#
my %norm_functions;
my %ext_functions;
my %wgl_functions;
my %egl_functions;
my %all_enums;

my %gl_types =
    (
        "EGLint" => "typedef khronos_int32_t EGLint;",
        "EGLNativeDisplayType" => "typedef void *EGLNativeDisplayType;",
        "EGLNativePixmapType" => "typedef void *EGLNativePixmapType;",
        "EGLNativeWindowType" => "typedef void *EGLNativeWindowType;",
    );
my @gl_types = ( sort keys %gl_types ); # also use an array to preserve declaration order

my %remapped_wgl_functions =
    (
     "ChoosePixelFormat" => "wglChoosePixelFormat",
     "DescribePixelFormat" => "wglDescribePixelFormat",
     "GetPixelFormat" => "wglGetPixelFormat",
     "GetEnhMetaFilePixelFormat" => 0,
     "SetPixelFormat" => "wglSetPixelFormat",
     "SwapBuffers" => "wglSwapBuffers",
     "wglUseFontBitmaps" => 0,
     "wglUseFontOutlines" => 0,
    );

my @extra_wgl_functions = ( "wglGetDefaultProcAddress" );

my %supported_wgl_extensions =
   (
    "WGL_ARB_create_context" => 1,
    "WGL_ARB_create_context_no_error" => 1,
    "WGL_ARB_create_context_profile" => 1,
    "WGL_ARB_extensions_string" => 1,
    "WGL_ARB_make_current_read" => 1,
    "WGL_ARB_multisample" => 1,
    "WGL_ARB_pbuffer" => 1,
    "WGL_ARB_pixel_format" => 1,
    "WGL_ARB_framebuffer_sRGB" => 1,
    "WGL_ARB_pixel_format_float" => 1,
    "WGL_ARB_render_texture" => 1,
    "WGL_ATI_pixel_format_float" => 1,
    "WGL_EXT_create_context_es2_profile" => 1,
    "WGL_EXT_extensions_string" => 1,
    "WGL_EXT_framebuffer_sRGB" => 1,
    "WGL_EXT_pixel_format_packed_float" => 1,
    "WGL_EXT_swap_control" => 1,
    "WGL_EXT_swap_control_tear" => 1,
    "WGL_NV_float_buffer" => 1,
    "WGL_NV_render_depth_texture" => 1,
    "WGL_NV_render_texture_rectangle" => 1,
    "WGL_NV_vertex_array_range" => 1,
    "WGL_WINE_pixel_format_passthrough" => 1,
    "WGL_WINE_query_renderer" => 1,
   );
my %supported_egl_extensions =
   (
    "EGL_EXT_pixel_format_float" => 1,
    "EGL_EXT_present_opaque" => 1,
    "EGL_KHR_create_context" => 1,
    "EGL_KHR_create_context_no_error" => 1,
    "EGL_KHR_no_config_context" => 1,
    "EGL_KHR_platform_android" => 1,
    "EGL_KHR_platform_wayland" => 1,
    "EGL_KHR_platform_x11" => 1,
    "EGL_MESA_platform_surfaceless" => 1,
   );

my %supported_apis =
    (
     "gl" => 1,
    );

sub is_supported_api($)
{
    my $api = shift;
    foreach my $i (split /\|/, $api)
    {
        return 1 if defined $supported_apis{$i};
    }
    return 0;
}

# some functions need a hand-written wrapper
sub needs_wrapper($$)
{
    my ($name, $func) = @_;

    return 0 if defined $manual_win_functions{$name};
    return 1 if defined $manual_unix_thunks{$name};

    # check if return value needs special handling
    (my $type = $func->[0]->textContent()) =~ s/ $//;
    return 1 if defined $remap_types{$type};
    # check if one of the arguments needs special handling
    foreach (@{$func->[1]})
    {
        $type = get_arg_type( $_ );
        return 1 if defined $remap_types{$type};
    }
    return 0;
}

sub parse_file($)
{
    my $file = shift;
    my $xml = XML::LibXML->load_xml( location => $file );
    my %functions;
    my %enums;

    # save all functions
    foreach my $command ($xml->findnodes("/registry/commands/command"))
    {
        my $proto = @{$command->findnodes("./proto")}[0];
        my $name = @{$command->findnodes("./proto/name")}[0];
        $proto->removeChild( $name );
        my @params = $command->findnodes("./param");
        $functions{$name->textContent()} = [ $proto, \@params ];
    }

    # save all enums
    foreach my $enum ($xml->findnodes("/registry/enums/enum"))
    {
        $enums{$enum->{name}} = $enum->{value};
    }

    # save all types
    foreach my $type ($xml->findnodes("/registry/types/type"))
    {
        next if $type->{api};
        my $name = @{$type->findnodes("./name")}[0];
        next unless $name;
        $name = $name->textContent;
        push @gl_types, $name unless $gl_types{$name};
        $gl_types{$name} = $type->textContent;
    }

    # generate norm functions
    foreach my $feature ($xml->findnodes("/registry/feature"))
    {
        if ($feature->{api} eq "wgl")
        {
            foreach my $cmd ($feature->findnodes("./require/command"))
            {
                my $name = $cmd->{name};
                if (defined $remapped_wgl_functions{$name})
                {
                    next unless $remapped_wgl_functions{$name};
                    $name = $remapped_wgl_functions{$name};
                }
                $wgl_functions{$name} = $functions{$cmd->{name}};
            }
            foreach my $name (@extra_wgl_functions)
            {
                $wgl_functions{$name} = $functions{$name} if defined $functions{$name};
            }
        }
        elsif ($feature->{api} eq "egl")
        {
            foreach my $cmd ($feature->findnodes("./require/command"))
            {
                my $name = $cmd->{name};
                $egl_functions{$name} = $functions{$cmd->{name}};
            }
            foreach my $enum ($feature->findnodes("./require/enum"))
            {
                $all_enums{$enum->{name}} = $enums{$enum->{name}};
            }
        }
        next unless defined $norm_categories{$feature->{name}};
        foreach my $cmd ($feature->findnodes("./require/command"))
        {
            $norm_functions{$cmd->{name}} = $functions{$cmd->{name}};
        }
        foreach my $enum ($feature->findnodes("./require/enum"))
        {
            $all_enums{$enum->{name}} = $enums{$enum->{name}};
        }
    }

    # generate extension functions from norm functions, if they are newer than the category
    foreach my $feature ($xml->findnodes("/registry/feature"))
    {
        next if defined $norm_categories{$feature->{name}};
        next unless is_supported_api( $feature->{api} );
        foreach my $cmd ($feature->findnodes("./require/command"))
        {
            my $name = $cmd->{name};
            next if $norm_functions{$name} || $ext_functions{$name};
            $ext_functions{$name} = [ $functions{$name}[0], $functions{$name}[1], [ $feature->{name} ] ];
        }
        foreach my $enum ($feature->findnodes("./require/enum"))
        {
            $all_enums{$enum->{name}} = $enums{$enum->{name}};
        }
    }

    # generate extension functions
    foreach my $ext ($xml->findnodes("/registry/extensions/extension"))
    {
        if ($ext->{supported} eq "wgl")
        {
            next unless defined $supported_wgl_extensions{$ext->{name}};
            foreach my $cmd ($ext->findnodes("./require/command"))
            {
                my $name = $cmd->{name};
                $ext_functions{$name} = [ $functions{$name}[0], $functions{$name}[1], [ $ext->{name} ] ];
            }
            foreach my $enum ($ext->findnodes("./require/enum"))
            {
                $all_enums{$enum->{name}} = $enums{$enum->{name}};
            }
            next;
        }
        if ($ext->{supported} eq "egl")
        {
            next unless defined $supported_egl_extensions{$ext->{name}};
            foreach my $cmd ($ext->findnodes("./require/command"))
            {
                my $name = $cmd->{name};
                $ext_functions{$name} = [ $functions{$name}[0], $functions{$name}[1], [ $ext->{name} ] ];
            }
            foreach my $enum ($ext->findnodes("./require/enum"))
            {
                $all_enums{$enum->{name}} = $enums{$enum->{name}};
            }
            next;
        }
        next unless is_supported_api( $ext->{supported} );
        foreach my $req ($ext->findnodes("./require"))
        {
            next unless !$req->{api} || $req->{api} eq "gl";
            foreach my $cmd ($req->findnodes("./command"))
            {
                my $name = $cmd->{name};
                next if $norm_functions{$name};
                if (!$ext_functions{$name})
                {
                    $ext_functions{$name} = [ $functions{$name}[0], $functions{$name}[1], [ $ext->{name} ] ];
                }
                else
                {
                    push @{$ext_functions{$name}->[2]}, $ext->{name};
                }
            }
        }
        foreach my $enum ($ext->findnodes("./require/enum"))
        {
            $all_enums{$enum->{name}} = $enums{$enum->{name}};
        }
    }
}

parse_file( "$cache/gl-$ogl_commit.xml" );
parse_file( "$cache/wgl-$ogl_commit.xml" );
parse_file( "$cache/egl-$egl_commit.xml" );
parse_file( "winegl.xml" );

#
# Generate the wgl.h file
#
open HEADER, ">$wgl_file" or die "cannot create $wgl_file";
print HEADER "/* Automatically generated from http://www.opengl.org/registry files; DO NOT EDIT! */\n\n";
print HEADER "#ifndef __WINE_WGL_H\n";
print HEADER "#define __WINE_WGL_H\n\n";

print HEADER "#include <stdarg.h>\n";
print HEADER "#include <stddef.h>\n";
print HEADER "#include <stdint.h>\n";
print HEADER "#include <windef.h>\n";
print HEADER "#include <winbase.h>\n";
print HEADER "#include <wingdi.h>\n";
print HEADER "#include <sys/types.h>\n";
print HEADER "\n";

print HEADER "#ifdef WINE_UNIX_LIB\n";
print HEADER "#define GL_NO_PROTOTYPES\n";
print HEADER "#define GLAPIENTRY\n";
print HEADER "#endif\n";
print HEADER "\n";

print HEADER "#ifndef GLAPIENTRY\n";
print HEADER "#define GLAPIENTRY __stdcall\n";
print HEADER "#endif\n\n";

print HEADER "#ifndef EGL_CAST\n";
print HEADER "#define EGL_CAST(t,x) ((t)(x))\n";
print HEADER "#endif\n\n";

foreach (@gl_types)
{
    my $type = $gl_types{$_};
    foreach my $t (keys %khronos_types) { $type =~ s/\s(\Q$t\E)\s/ $khronos_types{$t} /; }
    printf HEADER $type . "\n";
}
print HEADER "\n";

my $maxlen = 1;
foreach (keys %all_enums) { $maxlen = length($_) if length($_) > $maxlen; }
foreach (sort keys %all_enums)
{
    printf HEADER "#define %-*s %s\n", $maxlen, $_, $all_enums{$_};
}
print HEADER "\n";

print HEADER "#ifndef GL_NO_PROTOTYPES\n";
foreach (sort keys %norm_functions)
{
    my $decl_args = get_func_args( $norm_functions{$_}, 0 );
    my $func_ret = get_func_ret( $norm_functions{$_}, 0 );
    printf HEADER "%-10s GLAPIENTRY $_($decl_args);\n", $func_ret;
}
print HEADER "#endif\n\n";

foreach (sort keys %wgl_functions)
{
    my $decl_args = get_func_args( $wgl_functions{$_}, 0 );
    my $func_ret = get_func_ret( $wgl_functions{$_}, 0 );
    printf HEADER "typedef %-10s (GLAPIENTRY *PFN_$_)($decl_args);\n", $func_ret;
}

foreach (sort keys %egl_functions)
{
    my $decl_args = get_func_args( $egl_functions{$_}, 0 );
    my $func_ret = get_func_ret( $egl_functions{$_}, 0 );
    printf HEADER "typedef %-10s (GLAPIENTRY *PFN_$_)($decl_args);\n", $func_ret;
}

foreach (sort keys %norm_functions)
{
    my $decl_args = get_func_args( $norm_functions{$_}, 0 );
    my $func_ret = get_func_ret( $norm_functions{$_}, 0 );
    printf HEADER "typedef %-10s (GLAPIENTRY *PFN_$_)($decl_args);\n", $func_ret;
}

foreach (sort keys %ext_functions)
{
    my $decl_args = get_func_args( $ext_functions{$_}, 0 );
    my $func_ret = get_func_ret( $ext_functions{$_}, 0 );
    printf HEADER "typedef %-10s (GLAPIENTRY *PFN_$_)($decl_args);\n", $func_ret;
}
print HEADER "\n";

print HEADER "#define ALL_WGL_FUNCS";
foreach (sort keys %wgl_functions)
{
    printf HEADER " \\\n    USE_GL_FUNC(\%s)", $_;
}
print HEADER "\n\n";
print HEADER "#define ALL_WGL_EXT_FUNCS";
foreach (sort keys %ext_functions)
{
    next unless $_ =~ /^wgl/;
    printf HEADER " \\\n    USE_GL_FUNC(\%s)", $_;
}
print HEADER "\n\n";
print HEADER "#define ALL_EGL_FUNCS";
foreach (sort keys %egl_functions)
{
    next unless $_ =~ /^egl/;
    printf HEADER " \\\n    USE_GL_FUNC(\%s)", $_;
}
print HEADER "\n\n";
print HEADER "#define ALL_EGL_EXT_FUNCS";
foreach (sort keys %ext_functions)
{
    next unless $_ =~ /^egl/;
    printf HEADER " \\\n    USE_GL_FUNC(\%s)", $_;
}
print HEADER "\n\n";
print HEADER "#define ALL_GL_FUNCS";
foreach (sort keys %norm_functions)
{
    next if $_ =~ /^glDebugEntry/; # windows-specific function
    printf HEADER " \\\n    USE_GL_FUNC(\%s)", $_;
}
print HEADER "\n\n";
print HEADER "#define ALL_GL_EXT_FUNCS";
foreach (sort keys %ext_functions)
{
    next unless $_ =~ /^gl/;
    printf HEADER " \\\n    USE_GL_FUNC(\%s)", $_;
}
print HEADER "\n\n";

print HEADER "#endif /* __WINE_WGL_H */\n";
close HEADER;

#
# Now, generate the output files. First, the spec file.
#
open(SPEC, ">$spec_file") or die "cannot create $spec_file";

foreach (sort keys %norm_functions)
{
    printf SPEC "%s\n", generate_spec_entry( $_, $norm_functions{$_} );
}
foreach (sort keys %wgl_functions)
{
    printf SPEC "%s\n", generate_spec_entry( $_, $wgl_functions{$_} );
}

close(SPEC);

#
# Generate the unixlib.h file
#
open OUT, ">unixlib.h" or die "cannot create unixlib.h";
print OUT "/* Automatically generated from http://www.opengl.org/registry files; DO NOT EDIT! */\n\n";
print OUT "#ifndef __WINE_OPENGL32_UNIXLIB_H\n";
print OUT "#define __WINE_OPENGL32_UNIXLIB_H\n\n";

print OUT "#include <stdarg.h>\n";
print OUT "#include <stddef.h>\n\n";

print OUT "#include \"ntstatus.h\"\n";
print OUT "#define WIN32_NO_STATUS\n";
print OUT "#include \"windef.h\"\n";
print OUT "#include \"winbase.h\"\n";
print OUT "#include \"winternl.h\"\n";
print OUT "#include \"wingdi.h\"\n";
print OUT "#include \"ntuser.h\"\n\n";
print OUT "#include \"wine/wgl.h\"\n";
print OUT "#include \"wine/unixlib.h\"\n\n";

print OUT "struct process_attach_params\n";
print OUT "{\n";
print OUT "    UINT64 call_gl_debug_message_callback;\n";
print OUT "};\n\n";

foreach (sort keys %wgl_functions)
{
    next if defined $manual_win_functions{$_};
    print OUT generate_func_params($_, $wgl_functions{$_});
}
foreach (sort keys %norm_functions)
{
    next if defined $manual_win_functions{$_};
    print OUT generate_func_params($_, $norm_functions{$_});
}
foreach (sort keys %ext_functions)
{
    next if $_ =~ /^egl/; # unix-side only API
    next if defined $manual_win_functions{$_};
    print OUT generate_func_params($_, $ext_functions{$_});
}

print OUT "struct get_pixel_formats_params\n";
print OUT "{\n";
print OUT "    TEB *teb;\n";
print OUT "    HDC hdc;\n";
print OUT "    struct wgl_pixel_format *formats;\n";
print OUT "    unsigned int max_formats;\n";
print OUT "    unsigned int num_formats;\n";
print OUT "    unsigned int num_onscreen_formats;\n";
print OUT "};\n\n";

print OUT "enum unix_funcs\n";
print OUT "{\n";
print OUT "    unix_process_attach,\n";
print OUT "    unix_thread_attach,\n";
print OUT "    unix_process_detach,\n";
print OUT "    unix_get_pixel_formats,\n";
foreach (sort keys %wgl_functions)
{
    next if defined $manual_win_functions{$_};
    printf OUT "    unix_%s,\n", $_;
}
foreach (sort keys %norm_functions)
{
    next if defined $manual_win_functions{$_};
    printf OUT "    unix_%s,\n", $_;
}
foreach (sort keys %ext_functions)
{
    next if $_ =~ /^egl/; # unix-side only API
    next if defined $manual_win_functions{$_};
    printf OUT "    unix_%s,\n", $_;
}
print OUT "    funcs_count\n";
print OUT "};\n\n";

print OUT "struct gl_debug_message_callback_params\n";
print OUT "{\n";
print OUT "    struct dispatch_callback_params dispatch;\n";
print OUT "    UINT64 debug_callback; /* client pointer */\n";
print OUT "    UINT64 debug_user; /* client pointer */\n";
print OUT "    UINT32 source;\n";
print OUT "    UINT32 type;\n";
print OUT "    UINT32 id;\n";
print OUT "    UINT32 severity;\n";
print OUT "    UINT32 length;\n";
print OUT "    char message[1];\n";
print OUT "};\n\n";

print OUT "#define UNIX_CALL( func, params ) WINE_UNIX_CALL( unix_ ## func, params )\n\n";

print OUT "#endif /* __WINE_OPENGL32_UNIXLIB_H */\n";
close OUT;

#
# Generate the thunks.c file
#
open OUT, ">thunks.c" or die "cannot create thunks.c";
print OUT "/* Automatically generated from http://www.opengl.org/registry files; DO NOT EDIT! */\n\n";

print OUT "#include <stdarg.h>\n";
print OUT "#include <stddef.h>\n\n";

print OUT "#include \"ntstatus.h\"\n";
print OUT "#define WIN32_NO_STATUS\n";
print OUT "#include \"windef.h\"\n";
print OUT "#include \"winbase.h\"\n";
print OUT "#include \"wingdi.h\"\n\n";

print OUT "#include \"unixlib.h\"\n";
print OUT "#include \"private.h\"\n\n";
print OUT "#include \"wine/debug.h\"\n\n";
print OUT "WINE_DEFAULT_DEBUG_CHANNEL(opengl);\n";

foreach (sort keys %wgl_functions)
{
    next if defined $manual_win_functions{$_};
    next if defined $manual_win_thunks{$_};
    print OUT "\n" . generate_win_thunk($_, $wgl_functions{$_});
}
foreach (sort keys %norm_functions)
{
    next if defined $manual_win_functions{$_};
    next if defined $manual_win_thunks{$_};
    print OUT "\n" . generate_win_thunk($_, $norm_functions{$_});
}
foreach (sort keys %ext_functions)
{
    next if $_ =~ /^egl/; # unix-side only API
    next if defined $manual_win_functions{$_};
    next if defined $manual_win_thunks{$_};
    print OUT "\nstatic " . generate_win_thunk($_, $ext_functions{$_});
}
print OUT "\n";

foreach (sort keys %ext_functions)
{
    next if $_ =~ /^egl/; # unix-side only API
    next unless defined $manual_win_functions{$_} || $manual_win_thunks{$_};
    my $decl_args = get_func_args( $ext_functions{$_}, 0 );
    my $func_ret = get_func_ret( $ext_functions{$_}, 0 );
    printf OUT "extern %s WINAPI %s(%s);\n", $func_ret, $_, $decl_args;
}

print OUT "const void *extension_procs[] =\n";
print OUT "{\n";
foreach (sort keys %ext_functions)
{
    next if $_ =~ /^egl/; # unix-side only API
    printf OUT "    %s,\n", $_;
}
print OUT "};\n";

close OUT;

#
# Generate the unix_thunks.h file
#
open OUT, ">unix_thunks.h" or die "cannot create unix_thunks.h";
print OUT "/* Automatically generated from http://www.opengl.org/registry files; DO NOT EDIT! */\n\n";

foreach (sort keys %wgl_functions)
{
    next if !needs_wrapper( $_, $wgl_functions{$_} );
    print OUT generate_wrapper_declaration($_, $wgl_functions{$_}, 0);
}
foreach (sort keys %norm_functions)
{
    next if !needs_wrapper( $_, $norm_functions{$_} );
    print OUT generate_wrapper_declaration($_, $norm_functions{$_}, 0);
}
foreach (sort keys %ext_functions)
{
    next if $_ =~ /^egl/; # unix-side only API
    next if !needs_wrapper( $_, $ext_functions{$_} );
    print OUT generate_wrapper_declaration($_, $ext_functions{$_}, 0);
}

print OUT "\n#ifdef _WIN64\n";
print OUT "typedef ULONG PTR32;\n";

foreach (sort keys %wgl_functions)
{
    next unless defined $manual_wow64_wrappers{$_};
    print OUT generate_wrapper_declaration($_, $wgl_functions{$_}, 1);
}
foreach (sort keys %norm_functions)
{
    next unless defined $manual_wow64_wrappers{$_};
    print OUT generate_wrapper_declaration($_, $norm_functions{$_}, 1);
}
foreach (sort keys %ext_functions)
{
    next if $_ =~ /^egl/; # unix-side only API
    next unless defined $manual_wow64_wrappers{$_};
    print OUT generate_wrapper_declaration($_, $ext_functions{$_}, 1);
}

print OUT "#endif\n";
close OUT;

#
# Generate the unix_thunks.c file
#
open OUT, ">unix_thunks.c" or die "cannot create unix_thunks.c";
print OUT "/* Automatically generated from http://www.opengl.org/registry files; DO NOT EDIT! */\n\n";

print OUT "#if 0\n";
print OUT "#pragma makedep unix\n";
print OUT "#endif\n\n";

print OUT "#include <stdarg.h>\n";
print OUT "#include <stddef.h>\n\n";

print OUT "#include \"ntstatus.h\"\n";
print OUT "#define WIN32_NO_STATUS\n";
print OUT "#include \"windef.h\"\n";
print OUT "#include \"winbase.h\"\n";
print OUT "#include \"wingdi.h\"\n\n";

print OUT "#include \"unixlib.h\"\n";
print OUT "#include \"unix_private.h\"\n\n";
print OUT "#include \"wine/debug.h\"\n\n";

print OUT "WINE_DEFAULT_DEBUG_CHANNEL(opengl);\n\n";

print OUT "static GLboolean const_false;\n";
print OUT "static GLboolean const_true = 1;\n\n";

foreach (sort keys %wgl_functions)
{
    next if defined $manual_win_functions{$_};
    print OUT generate_unix_thunk($_, $wgl_functions{$_}, 0, "wgl");
}
foreach (sort keys %norm_functions)
{
    next if defined $manual_win_functions{$_};
    print OUT generate_unix_thunk($_, $norm_functions{$_}, 0, "gl");
}
foreach (sort keys %ext_functions)
{
    next if $_ =~ /^egl/; # unix-side only API
    next if defined $manual_win_functions{$_};
    print OUT generate_unix_thunk($_, $ext_functions{$_}, 0, "ext");
}

print OUT "const unixlib_entry_t __wine_unix_call_funcs[] =\n";
print OUT "{\n";
print OUT "    process_attach,\n";
print OUT "    thread_attach,\n";
print OUT "    process_detach,\n";
print OUT "    get_pixel_formats,\n";
foreach (sort keys %wgl_functions)
{
    next if defined $manual_win_functions{$_};
    printf OUT "    wgl_%s,\n", $_;
}
foreach (sort keys %norm_functions)
{
    next if defined $manual_win_functions{$_};
    printf OUT "    gl_%s,\n", $_;
}
foreach (sort keys %ext_functions)
{
    next if $_ =~ /^egl/; # unix-side only API
    next if defined $manual_win_functions{$_};
    printf OUT "    ext_%s,\n", $_;
}
print OUT "};\n\n";
print OUT "C_ASSERT(ARRAYSIZE(__wine_unix_call_funcs) == funcs_count);\n\n";

print OUT "#ifdef _WIN64\n\n";
print OUT "extern NTSTATUS wow64_thread_attach( void *args );\n";
print OUT "extern NTSTATUS wow64_process_detach( void *args );\n";
print OUT "extern NTSTATUS wow64_get_pixel_formats( void *args );\n\n";

foreach (sort keys %wgl_functions)
{
    next if defined $manual_win_functions{$_};
    print OUT generate_unix_thunk($_, $wgl_functions{$_}, 1, "wgl");
}
foreach (sort keys %norm_functions)
{
    next if defined $manual_win_functions{$_};
    print OUT generate_unix_thunk($_, $norm_functions{$_}, 1, "gl");
}
foreach (sort keys %ext_functions)
{
    next if $_ =~ /^egl/; # unix-side only API
    next if defined $manual_win_functions{$_};
    print OUT generate_unix_thunk($_, $ext_functions{$_}, 1, "ext");
}

print OUT "\nconst unixlib_entry_t __wine_unix_call_wow64_funcs[] =\n";
print OUT "{\n";
print OUT "    process_attach,\n";
print OUT "    wow64_thread_attach,\n";
print OUT "    wow64_process_detach,\n";
print OUT "    wow64_get_pixel_formats,\n";
foreach (sort keys %wgl_functions)
{
    next if defined $manual_win_functions{$_};
    printf OUT "    wow64_wgl_%s,\n", $_;
}
foreach (sort keys %norm_functions)
{
    next if defined $manual_win_functions{$_};
    printf OUT "    wow64_gl_%s,\n", $_;
}
foreach (sort keys %ext_functions)
{
    next if $_ =~ /^egl/; # unix-side only API
    next if defined $manual_win_functions{$_};
    printf OUT "    wow64_ext_%s,\n", $_;
}
print OUT "};\n\n";
print OUT "C_ASSERT(ARRAYSIZE(__wine_unix_call_wow64_funcs) == funcs_count);\n\n";

print OUT "#endif\n\n";

foreach (sort keys %wgl_functions)
{
    next if defined $manual_win_functions{$_};
    print OUT generate_null_func($_, $wgl_functions{$_});
}
printf OUT "static void null_get_pixel_formats( struct wgl_pixel_format *formats, UINT max_formats,\n";
printf OUT "                                    UINT *num_formats, UINT *num_onscreen_formats )\n";
printf OUT "{\n";
printf OUT "    ERR( \"unsupported\\n\" );\n";
printf OUT "    *num_formats = *num_onscreen_formats = 0;\n";
printf OUT "}\n";
foreach (sort keys %norm_functions)
{
    next if defined $manual_win_functions{$_};
    print OUT generate_null_func($_, $norm_functions{$_});
}
foreach (sort keys %ext_functions)
{
    next if $_ =~ /^egl/; # unix-side only API
    next if defined $manual_win_functions{$_};
    print OUT generate_null_func($_, $ext_functions{$_});
}
print OUT "\n";

print OUT "struct opengl_funcs null_opengl_funcs =\n";
print OUT "{\n";
print OUT "    .p_get_pixel_formats = null_get_pixel_formats,\n";
foreach (sort keys %wgl_functions)
{
    next if defined $manual_win_functions{$_};
    print OUT "    .p_$_ = null_$_,\n";
}
foreach (sort keys %norm_functions)
{
    next if defined $manual_win_functions{$_};
    print OUT "    .p_$_ = null_$_,\n";
}
foreach (sort keys %ext_functions)
{
    next if $_ =~ /^egl/; # unix-side only API
    next if defined $manual_win_functions{$_};
    print OUT "    .p_$_ = null_$_,\n";
}
print OUT "};\n";

# Then the table giving the string <-> function correspondence */
my $count = keys %ext_functions;
print OUT "\nconst int extension_registry_size = $count;\n";
print OUT "const struct registry_entry extension_registry[$count] =\n";
print OUT "{\n";
foreach (sort keys %ext_functions)
{
    next if $_ =~ /^egl/; # unix-side only API
    my $func = $ext_functions{$_};
    printf OUT "    { \"%s\", \"%s\", offsetof(struct opengl_funcs, p_$_) },\n", $_, join(" ", sort @{$func->[2]});
}
print OUT "};\n";

close OUT;
